package com.scf.fruit.business.login.web;

import com.scf.fruit.business.login.po.req.FruitUserReq;
import com.scf.fruit.business.login.po.req.LoginReq;
import com.scf.fruit.shiro.FruitUserService;
import com.scf.fruit.user.FruitUserDto;
import com.scf.fruit.util.IDUtil;
import com.scf.fruit.util.SecUtils;
import com.scf.fruit.util.SpringCglibBeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

/**
 * @author : 孙超飞
 * @title :
 * @description :
 * @date : 2018-04-23 11:44
 */
@Controller
@RequestMapping(value = "/login",produces = "application/json")
public class LoginController {
@Resource
private FruitUserService fruitUserService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestBody LoginReq req) throws InvalidKeySpecException, NoSuchAlgorithmException {
        //添加用户认证信息
        Subject subject = SecurityUtils.getSubject();
        FruitUserDto byMobile = fruitUserService.findByMobile(req.getMobile());
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                req.getMobile(),
                Base64.getEncoder().encodeToString((SecUtils.getEncryptedPassword(req.getPassword(),byMobile.getSalt()))));
        //进行验证，这里可以捕获异常，然后返回对应信息
        try{
            subject.login(usernamePasswordToken);
            return "/html/index.html";
        }catch (Exception e){
            return "/html/error.html";
        }

    }

    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    @ResponseBody
    public String addUser(@RequestBody FruitUserReq req) throws NoSuchAlgorithmException, InvalidKeySpecException {
        FruitUserDto dto = SpringCglibBeanUtils.convert(req, FruitUserDto.class);
        dto.setSalt(SecUtils.generateSalt());
        dto.setPassword(SecUtils.getEncryptedPassword(req.getPassword(),dto.getSalt()));
        fruitUserService.insert(dto);
        return "addUser is ok! \n" + dto;
    }

}
